package com.tangsm.spring.boot.api.exception;

import cn.hutool.core.util.ArrayUtil;
import com.tangsm.spring.boot.api.base.IResultCode;
import com.tangsm.spring.boot.api.enums.ResultCode;

import java.text.MessageFormat;

/**
 * 自定义业务异常
 *
 * @author tangsm
 */
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 1921586608127303750L;

    private IResultCode resultCode = ResultCode.ERROR;

    private Object[] msgParams = null;

    /**
     * 无参构造，默认服务异常 {@link ResultCode}.ERROR
     */
    public BusinessException() {
        super();
    }

    /**
     * 有参构造，按响应状态码枚举构建业务异常
     *
     * @param resultCode 响应状态码枚举
     */
    public BusinessException(IResultCode resultCode) {
        super(resultCode.getMsg());
        this.resultCode = resultCode;
    }

    /**
     * 有参构造，按响应状态码枚举构建业务异常
     *
     * @param resultCode 响应状态码枚举
     * @param msgParams  占位符可变长参数
     */
    public BusinessException(IResultCode resultCode, Object... msgParams) {
        super(ArrayUtil.isEmpty(msgParams) ? resultCode.getMsg() : MessageFormat.format(resultCode.getMsg(), msgParams));
        this.resultCode = resultCode;
        this.msgParams = msgParams;
    }

    @Override
    public String getMessage() {
        if (ArrayUtil.isEmpty(this.msgParams)) {
            return this.resultCode.getMsg();
        }

        return MessageFormat.format(this.resultCode.getMsg(), this.msgParams);
    }

    public IResultCode getResultCode() {
        return resultCode;
    }

    public Object[] getMsgParams() {
        return msgParams;
    }
}
